﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using UIShare;
using EFong.View.Proxy;
using EFong.Contract;

namespace EFong.View.Financing
{
    public partial class Frm_VendorOtherSettlement : BasicMdiChildForm
    {
        private Proxy.FinanceServiceProxy _financeServiceProxy { get { return Proxy.FinanceServiceProxy.GetInstance(); } }
        private Proxy.MasterServiceProxy _masterProxy { get { return Proxy.MasterServiceProxy.GetInstance(); } }
        private Proxy.BaseServiceProxy _baseServiceProxy { get { return Proxy.BaseServiceProxy.GetInstance(); } }

        private List<RVendor> vendorList = null;
        private List<Order> orderList = null;
        //private List<其他支付单> usedOrderList = null;

        private Contract.Vendor _vendor;
        public Contract.Vendor Vendor
        {
            get { return _vendor; }
            set
            {
                _vendor = value;
                onVendorChanged();
            }
        }

        public Frm_VendorOtherSettlement()
        {
            InitializeComponent();
            cmb_BankAccount.ReadOnly(true);
        }

        protected override void InitFields()
        {
        }

        protected override void LoadDatas()
        {
            orderList = _financeServiceProxy.GetVendorOrders().ReturnValue;
            grd_Orders.DataSource = orderList;
            //this.cmb_Customer.Properties.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            vendorList = _masterProxy.GetAllVendor().ReturnValue;
            bds_Customer.BindingData(vendorList);
            this.cmb_BankAccount.Properties.BindingData(_masterProxy.GetAllBankAccount().ReturnValue);
            this.cmb_Currency.Properties.BindingData(_baseServiceProxy.GetAllCurrency().ReturnValue);
            this.dte_PostingDate.DateTime = DateTime.Now;
            this.dte_SettlementDate.DateTime = DateTime.Now;

        }

        protected override void Events()
        {
            this.cmb_Vendor.EditValueChanged += (s, e) =>
            {
                loadVendor();
            };

            //this.gv_Orders.CellValueChanged += (s, e) =>
            //{
            //    refreshSelect();
            //};

            this.cmb_PayType.SelectedIndexChanged += (s, e) =>
            {
                if (ViewState == ViewStates.EDIT) { return; }

                this.cmb_BankAccount.SetValue(default(Contract.BankAccount));
                this.cmb_BankAccount.ReadOnly(this.cmb_PayType.SelectedIndex <= 0);
            };

            this.cmb_BankAccount.SelectedIndexChanged += (s, e) =>
            {
                Contract.BankAccount bankAccount = cmb_BankAccount.GetValue() as Contract.BankAccount;
                if (bankAccount == null)
                {
                    txt_BankAccountAmount.Text = "0";
                    cmb_Currency.ReadOnly(false);
                }
                else
                {
                    txt_BankAccountAmount.Text = string.Format("{0} {1}", bankAccount.Currency.Code, bankAccount.Amount);
                    cmb_Currency.ReadOnly(true);
                    cmb_Currency.SetValue(bankAccount.Currency);
                }
            };
            this.gv_Orders.CellValueChanging += (s, e) =>
            {
                if (e.Column != colSelect)
                    return;

                Order order = gv_Orders.GetRow(e.RowHandle) as Order;
                if (order == null)
                    return;
                this.gv_Orders.BeginDataUpdate();
                selectOrders(order, !order.IsSelect);
                this.gv_Orders.EndDataUpdate();

                if (order.IsSelect) 
                {
                    RVendor vendor = vendorList.FirstOrDefault(v => v.Name == order.VendorText);
                    this.cmb_Vendor.SetValue(vendor);
                    this._vendor = _masterProxy.GetVendorByID(vendor.ID).ReturnValue;
                }

                refreshSelect();
            };
        }

        private void selectOrders(Order order, bool isSelect)
        {
            orderList.ForEach(o => 
            {
                if (o.ID == order.ID)
                {
                    o.IsSelect = isSelect;
                }
                else 
                {
                    if (isSelect) 
                    {
                        if (o.VendorText != order.VendorText)
                            o.IsSelect = false;
                    }
                }
            });
        }

        private void refreshSelect()
        {
            decimal totalReceive = 0;
            foreach (Order order in (grd_Orders.DataSource as List<Order>))
            {
                if(order.IsSelect)
                    totalReceive += order.Money;
            }

            this.txt_TotalAccountReceivable.Text = totalReceive.ToString();

            grd_Orders.RefreshDataSource();
            this.cmb_BankAccount.Properties.BindingData(_masterProxy.GetAllBankAccount().ReturnValue);
        }

        void loadVendor()
        {
            RVendor rVendor = this.cmb_Vendor.GetValue() as RVendor;
            if (rVendor == null)
                return;
            Vendor = _masterProxy.GetVendorByID(rVendor.ID).ReturnValue;
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Save":
                    this.save();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private void save()
        {
            if (Vendor == null)
            {
                MsgBox.Error("请先选择供应商");
                return;
            }

            VendorOtherSettlement vendorSettlement = new VendorOtherSettlement();
            vendorSettlement.Amount = txt_Amount.GetValue();
            vendorSettlement.BankAccount = cmb_BankAccount.GetValue() as Contract.BankAccount;
            vendorSettlement.CheckNo = txt_CheckNo.GetText();
            vendorSettlement.Vendor = Vendor;
            vendorSettlement.OrderList = getOrderList();
            vendorSettlement.PaymentType = cmb_PayType.GetValue() as string;
            vendorSettlement.PostingDate = dte_PostingDate.GetValue(DateTime.MinValue);
            vendorSettlement.Remark = txt_Remark.GetText();
            vendorSettlement.SettlementDate = dte_SettlementDate.GetValue(DateTime.MinValue);
            vendorSettlement.ExchangeRate = txtExchangeRate.GetValue();
            vendorSettlement.Currency = cmb_Currency.GetValue() as Currency;

            if (_financeServiceProxy.VendorSettle(vendorSettlement).IsSuccess)
            {
                MsgBox.Info("保存成功");
                resetData();
                this.cmb_Vendor.SetValue(null);
                this.txt_Amount.SetValue(0);
                this.txt_BankAccountAmount.SetText(string.Empty);
                //loadCustomer();
                //refreshSelect();
            }
        }

        private void resetData()
        {
            orderList = _financeServiceProxy.GetVendorOrders().ReturnValue;
            grd_Orders.DataSource = orderList;
        }

        private List<Order> getOrderList()
        {
            List<Order> resultList = (from o in orderList
                                         where o.VendorText == Vendor.Name
                                         select o).ToList();

            return resultList;

        }


        void onVendorChanged()
        {
            if (Vendor == null)
            {
                // clear customer datas
                List<Order> list = new List<Order>();
                this.grd_Orders.DataSource = list;
                orderList.ForEach(o => o.IsSelect = false);
            }
            else
            {
                orderList.ForEach(o => o.IsSelect = false);

                List<Order> usedOrderList = (from o in orderList
                                             where o.VendorText == Vendor.Name
                                             select o).ToList();
                usedOrderList.ForEach(o => o.IsSelect = true);
                this.grd_Orders.DataSource = usedOrderList;
            }

            refreshSelect();
        }
    }
}
